<template>
  <div v-loading="loading" class="role-edit">
    <el-form :model="form">
      <el-tree
        :data="permissions"
        show-checkbox
        node-key="id"
        :props="{label: 'permissionName',children: 'childList'}"
        :default-checked-keys="form.fkPermissions"
        @check="checkChange"
      >
      </el-tree>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('change-state',false)">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.dialog-footer {
  text-align: center;
}
.el-cascader {
  width: 100%;
}
</style>
<script>
export default {
  data() {
    return {
      form: {
        fkRole: '',
        fkPermissions: [] // 选中的id列表
      },
      permissions: [],
      loading: false
    }
  },
  beforeDestroy() {
    this.$off('change-state')
  },
  methods: {
    initDialogData(_id) {
      this.form.fkRole = _id
      this.loading = true
      this.$axios.all([this.$axios.get(`/org/permission/get-tree-list`), this.$axios.get(`/org/role/permission/get-list-by-role?fkRole=` + _id)])
        .then(this.$axios.spread((res1, res2) => {
          this.loading = false
          if (res1.data.code === 200 && res1.data.obj) {
            this.permissions = res1.data.obj
          }
          if (res2.data.code === 200 && res2.data.obj) {
            this.form.fkPermissions = res2.data.obj
          }
        }))
    }, // 节点选中状态发生变化时
    checkChange(res1, res2) {
      this.form.fkPermissions = res2.checkedKeys
    },
    save() {
      this.loading = true
      this.$axios.put('/org/role/permission/update', this.form)
        .then(res => {
          this.loading = false
          if (res.data.code === 200) {
            this.$emit('change-state', false)
            this.$message.success(res.data.msg)
          } else {
            this.$message.success(res.data.msg)
          }
        }).catch(() => {
          this.loading = false
        })
    }
  }
}
</script>
